package com.boot.common.filter;

import com.boot.common.encrypt.RSAEncrypt;
import com.boot.common.exception.RRException;
import com.google.common.collect.Maps;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Enumeration;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;

public class ModifyParametersWrapper extends HttpServletRequestWrapper {

	
	private final Map<String, Object> parameterMap = Maps.newHashMap();

    public ModifyParametersWrapper(final HttpServletRequest request) {
        super(request);

        for (final Entry<String, String[]> e : request.getParameterMap().entrySet()) {
//        	System.out.println("参数名："+e.getKey());
//        	System.out.println("参数值："+e.getValue()[0]);
        	String val = RSAEncrypt.decrypt(e.getValue()[0], RSAEncrypt.private_key);
        	if(val==null){
        		throw new RRException("参数解析错误，疑似不合法请求！！！",-999);

        	}
        	
            this.parameterMap.put(e.getKey(), val);
        }
        //获取解密方式
//        final String storeKey = ParamFilter.keyCache.getAESKey("xxx");
//        ParamFilter.coder.decode(this.parameterMap, storeKey);
    }

    // 重写几个HttpServletRequestWrapper中的方法

    /**
     * 获取所有参数名
     *
     * @return 返回所有参数名
     */
    /*重写getParameter方法
     * 对请求结果进行过滤*/
    @Override
    public Enumeration<String> getParameterNames() {
        final Vector<String> vector = new Vector<>(this.parameterMap.keySet());
        return vector.elements();
    }

    /*重写getParameterValues方法
     * 通过循环取出每一个请求结果
     * 再对请求结果进行过滤*/
    @Override
    public String[] getParameterValues(final String name) {
        final Object result = this.parameterMap.get(name);
        if (result == null) {
            return null;
        }
        return new String[] {result.toString()};
    }

    @Override
    public String getParameter(final String name) {
        final Object value = this.parameterMap.get(name);
        return value.toString();
    }

    @Override
    public Map<String, String[]> getParameterMap() {

        final Map<String, String[]> result = Maps.newHashMap();
        for (final Entry<String, Object> e : this.parameterMap.entrySet()) {
            Object value = e.getValue();
            if(value == null){
                continue;
            }
            result.put(e.getKey(), new String[] {e.getValue().toString()});
        }
        return result;
    }

}
